<?php

/**
 * Description of plgSystemZooTwittertweet
 *
 * @version     1.0
 * @author Daniel Eliasson <joomla at stilero.com>
 * @copyright  (C) 2012-jan-01 Stilero Webdesign http://www.stilero.com
 * @category Plugins
 * @license	GPLv2
 * 
 * Joomla! is free software. This version may have been modified pursuant
 * to the GNU General Public License, and as distributed it includes or
 * is derivative of works licensed under the GNU General Public License or
 * other free or open source software licenses.
 * 
 * This file is part of plgSystemZooTwittertweet.
 * 
 * plgSystemZooTwittertweet is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * plgSystemZooTwittertweet is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with plgSystemZooTwittertweet.  If not, see <http://www.gnu.org/licenses/>.
 * 
 */
// no direct access
defined('_JEXEC') or die('Restricted access');


// import library dependencies
jimport('joomla.plugin.plugin');

//Load the classes
$classfolder='zootwittertweetclasses';
JLoader::register('stlTweetControllerClass', dirname(__FILE__).DS.$classfolder.DS.'stlTweetControllerClass.php');
JLoader::register('stlShareControllerClass', dirname(__FILE__).DS.$classfolder.DS.'stlShareControllerClass.php');
JLoader::register('simpleTwitterClass', dirname(__FILE__).DS.$classfolder.DS.'simpleTwitterClass.php');
JLoader::register('stileroOauthTweetClass', dirname(__FILE__).DS.$classfolder.DS.'stileroOauthTweetClass.php');


class plgSystemZootwittertweet extends JPlugin {
    public $app;
    public $params;
    var $k2Item;
    var $config;
    var $twitterFormToken;
    var $fullTweet;
    var $inBackend;
    var $errorOccured;
    var $CheckClass;
    const HTTP_STATUS_FOUND = '302';
    const HTTP_STATUS_OK = '200';
    const HTTP_STATUS_UNAUTHORIZED = '401'; //Returned from Twitter on wrong OAuth details
    const HTTP_STATUS_FORBIDDEN = '403'; //Returned from Twitter on duplicate tweets


    function plgSystemZootwittertweet($subject) {
        parent::__construct($subject);
        $plugin = JPluginHelper::getPlugin('system', 'zootwittertweet');
        $this->params = new JParameter($plugin->params);
        JPlugin::loadLanguage('plg_system_zootwittertweet', JPATH_ADMINISTRATOR, 'en-GB', true);
        JPlugin::loadLanguage('plg_system_zootwittertweet', JPATH_ADMINISTRATOR, null, true);
        //JPlugin::loadLanguage('plg_system_zootwittertweet', JPATH_ADMINISTRATOR);
        $this->errorOccured = FALSE;
        $this->config = array(
        'shareLogTableName'     =>      '#__zootwittertweet_log',
        'twitterUsername'       =>      $this->params->def('username'),
        'twitterPassword'       =>      $this->params->def('password'),
        'oauthConsumerKey'      =>      $this->params->def('oauth_consumer_key'),
        'oauthConsumerSecret'   =>      $this->params->def('oauth_consumer_secret'),
        'oauthUserKey'          =>      $this->params->def('oauth_user_key'),
        'oauthUserSecret'       =>      $this->params->def('oauth_user_secret'),
        'twitterMaxHashTags'    =>      3,
        'useOauth'              =>      $this->params->def('oauth_enabled'),
        'twControllerClassName' =>      'stlTweetControllerClass',
        'categoriesToShare'     =>      $this->params->def('section_id'),
        'shareDelay'            =>      $this->params->def('delay'),
        'articlesNewerThan'     =>      $this->params->def('items_newer_than'),
        'useMetaAsHashTag'      =>      $this->params->def('metahash')
        );
  
    }

    function onAfterInitialise() {
        //Check if the component is installed
        if (!JComponentHelper::getComponent('com_zoo', true)->enabled) {
            return;
        }
        // load ZOO config
        jimport('joomla.filesystem.file');
        if (!JFile::exists(JPATH_ADMINISTRATOR.'/components/com_zoo/config.php') || !JComponentHelper::getComponent('com_zoo', true)->enabled) {
                return;
        }
        require_once(JPATH_ADMINISTRATOR.'/components/com_zoo/config.php');
        // make sure App class exists
        if (!class_exists('App')) {
                return;
        }
        $zoo = App::getInstance('zoo');
        $zoo->event->dispatcher->connect('item:saved', array($this, 'itemSaved'));
        $zoo->event->dispatcher->connect('item:afterdisplay', array($this, 'itemDisplayed'));
    }


    public function itemSaved($event){
        $this->inBackend = true;
        $this->setupClasses();
        $articleObject = $this->getArticleObjectFromZooEvent($event);
        $this->CheckClass->setArticleObject($articleObject);
        $this->sendTweet();
        return;
    }
    
     public function itemDisplayed($event){
        $this->inBackend = false;
        $this->setupClasses();
        $articleObject = $this->getArticleObjectFromZooEvent($event);
        $this->CheckClass->setArticleObject($articleObject);
        $this->sendTweet();
        return;
    }

    public function setupClasses() {
        $this->CheckClass = new $this->config['twControllerClassName']( 
            array(
            'twitterUsername'       =>      $this->config['twitterUsername'],
            'twitterPassword'       =>      $this->config['twitterPassword'],
            'useOauth'              =>      $this->config['useOauth'],
            'oauthConsumerKey'      =>      $this->config['oauthConsumerKey'],
            'oauthConsumerSecret'   =>      $this->config['oauthConsumerSecret'],
            'oauthUserKey'          =>      $this->config['oauthUserKey'],
            'oauthUserSecret'       =>      $this->config['oauthUserSecret'],
            'shareLogTableName'     =>      $this->config['shareLogTableName'],
            'pluginLangPrefix'      =>      'PLG_SYSTEM_ZOOTWITTERTWEET_',
            'categoriesToShare'     =>      $this->config['categoriesToShare'],
            'shareDelay'            =>      $this->config['shareDelay'],
            'articlesNewerThan'     =>      $this->config['articlesNewerThan'],
            'useMetaAsHashTag'      =>      $this->config['useMetaAsHashTag']
            )
        );
    }
        
    public function sendTweet() {
        if( !$this->isInitialChecksOK() ) {
            $this->displayMessage(JText::_($this->CheckClass->error['message']) , $this->CheckClass->error['type']);
            return;
        }
        if ($this->CheckClass->tweet() ) {
            $tweet = urldecode($this->CheckClass->fullTweet);
            $this->displayMessage(JText::_('Tweeted: ').$tweet);
            return;
        }else{
            $this->displayMessage(JText::_($this->CheckClass->error['message']) , $this->CheckClass->error['type']);
            return;
        }
    }
               
    public function getArticleObjectFromZooEvent($zooEvent) {
        $item = $zooEvent->getSubject();
        $params = $zooEvent->getParameters();
        $articleObject = new stdClass();
        $articleObject->id = $item->id;
        $articleObject->language= "";
        $articleObject->link = $item->alias;
        $articleObject->full_url = $this->getFullURL($item->id);
        $articleObject->tags = $item->getTags();
        $articleObject->title = $item->name;
        $articleObject->catid = $item->params->get('config.primary_category');
        $articleObject->access = $item->access;
        $articleObject->publish_up = $item->publish_up;
        $articleObject->published = $item->state; 
        return $articleObject;
    }
//    /*
//     * Takes an array with tags and returns a tags class array
//     */
//    public function getTagsObjectArray($tagsArray){
//        foreach ($tagsArray as $key => $value) {
//            $tagsObject = new stdClass();
//            $tagsObject->name = trim($value);
//            $tagsObjectArray[]=$tagsObject;
//        }
//        return $tagsObjectArray;
//    }
    
    public function displayMessage($msg, $messageType = "") {
        $isSetToDisplayMessages = ($this->params->def('pingmessages')==0)?false:true;
        if( ! $isSetToDisplayMessages || ! $this->inBackend ){
            return;
        }else{
            JFactory::getApplication()->enqueueMessage( $msg, $messageType);
        }
    }
        
    private function doInitialChecks() {
        $this->CheckClass->isServerSupportingRequiredFunctions();
        $this->CheckClass->isServerSafeModeDisabled();
        if ( $this->config['useOauth'] ){
            $this->CheckClass->isOauthDetailsEntered();
        }else{
            $this->CheckClass->isLoginDetailsEntered();
        }
        $this->CheckClass->isArticleObjectIncluded();
        $this->CheckClass->isItemActive();
        $this->CheckClass->isItemPublished();
        $this->CheckClass->isItemNewEnough();
        $this->CheckClass->isItemPublic();
        $this->CheckClass->isCategoryToShare();
        $this->CheckClass->prepareTables();
        $this->CheckClass->isSharingToEarly();
        $this->CheckClass->isItemAlreadyShared();
        return $this->CheckClass->error;
    }
        
    public function isInitialChecksOK() {
        $errorMessage = $this->doInitialChecks();
        if ( $errorMessage != FALSE ) {
            return FALSE;
        }
        return TRUE;
    }
        
    public function getFullURL($k2ItemID) {
        $urlQuery = "?option=com_zoo&task=item&item_id=".$k2ItemID;
        $fullURL = JURI::root()."index.php".$urlQuery;
        return $fullURL;
    }
 


//End Class
}